﻿using HalconDotNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AIVision.PhotoModule
{
    public class CameraAgent
    {
        private readonly CameraCfgModel cameraCfgModel;
        private BaseCamera camera;
        private string photoCachePath;
        public CameraAgent(CameraCfgModel cameraCfgModel)
        {
            this.cameraCfgModel = cameraCfgModel;
            if (!string.IsNullOrEmpty(cameraCfgModel.PhotoCachePath))
                photoCachePath = cameraCfgModel.PhotoCachePath;
            else
                photoCachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PhotoTemp");
        }

        public bool TriggerPhoto(ref string PhotoPath,ref string ErrMsg)
        {
            try
            {
                HObject image = camera.OneGrap();
                if (image != null)
                {
                    PhotoPath = Path.Combine(photoCachePath, Guid.NewGuid().ToString() + ".bmp");
                    HOperatorSet.WriteImage(image, "bmp", 0, PhotoPath);
                    if (File.Exists(PhotoPath))
                        return true;
                    else
                    {
                        ErrMsg = "拍照成功，存储失败!";
                        return false;
                    }
                }
                else
                {
                    ErrMsg = "拍照失败，对象为空";
                    return false;
                }
            }
            catch (Exception ex)
            {
                ErrMsg = $"拍照失败:{ex.Message}";
                return false;
            }
        }

        public void Init()
        {
            try
            {
                //初始化相机
                camera = new HKCamerSDK();//根据我们需要开启的相机品牌去实例化化相机类
                camera.CamerName = cameraCfgModel.Name;
                var list = camera.FindCamer();
                var v = camera.OpenCamer(cameraCfgModel.CameraHardKey);
                if (!v)
                {
                    throw new Exception($"相机{camera.CamerName}打开失败");
                }
                //初始化照片路径文件夹
                if (!Directory.Exists(photoCachePath))
                    Directory.CreateDirectory(photoCachePath);

            }
            catch (Exception ex)
            {
                throw new Exception($"相机{camera.CamerName}打开失败");
            }
        }


    }
}
